import React, { useState, useEffect } from 'react'
import { Col, Form, Input, Button, Avatar, Modal, Upload, Icon, message } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import { getIconList, uploadIcon, deleteIcon } from '@/services/supplier/category/iconType'

function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

const IconType = props => {
  const { form } = props
  const { getFieldDecorator } = form
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(999)
  const [iconList, setIconList] = useState([])
  const [visible, setVisible] = useState(false)
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState('')

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)

    })
  }

  useEffect(() => {
    init()
  }, [])

  const init = async () => {
    await getIconLists()
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return (
      <Col span={8}>
        <Form.Item label={`名称`}>
          {getFieldDecorator(`id`, {})
            (<input />)}
        </Form.Item>
      </Col>
    )
  }
  // 按钮处理
  const handleBtn = type => {
    showModal()
  }
  // 获取分类图标列表
  const getIconLists = async () => {
    let params = {
      pageNo,
      pageSize
    }
    let res = await getIconList(params)
    if (res.code === '0') {
      setIconList(res.data)
    } else {
      alert(res.msg)
    }
  }
  // 渲染图标列表
  const RenderIconList = () => {
    let items = []
    iconList.forEach(item => {
      items.push(<span key={item.id} style={{ display: 'inline-block', margin: '6px', textAlign: 'center' }}>
        <Avatar size="large" src={item.iconUrl} style={{ display: 'block', marginBottom: '6px' }} />
        <span style={{ background: '#fff', padding: '2px 5px', fontSize: '12px', border: '1px solid #eee' }} onClick={() => deleteIcons(item.id)}>删除</span>
      </span>)
    })
    return (<div>{items}</div>)
  }
  const showModal = () => {
    setVisible(true)
  }

  const handleOk = e => {
    console.log(e)
    setVisible(false)
  }

  const handleCancel = e => {
    setVisible(false)
  }
  const handleChange = info => {
    if (info.file.status === 'uploading') {
      setLoading(true)
      return;
    }
    if (info.file.status === 'done') {
      // Get this url from response in real world.
      getBase64(info.file.originFileObj, imageUrl => {
          setImageUrl(imageUrl)
          setLoading(false)
        }
      );
    }
  };
  const uploadButton = (
    <div>
      <Icon type={loading ? 'loading' : 'plus'} />
      <div className="ant-upload-text">Upload</div>
    </div>
  );
  // 上传图标
  const uploadIcons = async (file) => {
    let params = {
      albumName: '临时相册',
      albumIsPlatform: true,
      files: file
    }
    let res = await uploadIcon()
    if (res.code === '0') {
      console.log(res.data);
    } else {
      alert(res.msg)
    }
  }
  async function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
  }

  const pp = {
    name: "avatar",
    listType: "picture-card",
    className: "avatar-uploader",
    showUploadList: false,
    beforeUpload: beforeUpload,
    onChange: handleChange,
    previewFile(file) {
      console.log('Your upload file:', file)

    }
  }
  // 删除图标
  const deleteIcons = async (id) => {
    let idList = []
    idList.push(id)
    let params = {
      idList
    }
    let res = await deleteIcon(params)
    if (res.code === '0') {
      alert(res.msg)
      init()
    } else {
      alert(res.msg)
    }
  }

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <RenderIconList />
      <Modal
        title="添加图标"
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <p>请选择图标:(建议尺寸104*104）</p>
        <Upload {...pp}>
          {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
        </Upload>
      </Modal>
    </PageHeaderWrapper>
  )
}

export default Form.create()(IconType)
